#define BUFFER_MANAGER
#include "buffer_manager.h"
#include "server_listener.h"

int add_to_buffer(char *msg)
{
	char	*new_msg;

	pthread_mutex_lock(&buffer_lock);

	while (buffer.size() >= MAX_BUFFER_SIZE)
		pthread_cond_wait(&buffer_pop_flag, &buffer_lock);
	
	new_msg = (char *)malloc(strlen(msg) + 1);
	strcpy(new_msg, msg);
	buffer.push(new_msg);

	pthread_mutex_unlock(&buffer_lock);
	pthread_cond_signal(&buffer_add_flag);
	return 0;
}

char *pop_from_buffer()
{
	char *msg;

	pthread_mutex_lock(&buffer_lock);

	while (buffer.size() <= 0)
		pthread_cond_wait(&buffer_add_flag, &buffer_lock);

	msg = buffer.front();
	buffer.pop();

	pthread_mutex_unlock(&buffer_lock);
	pthread_cond_signal(&buffer_pop_flag);

	return msg;
}

void del_from_buffer(char *msg)
{
	free(msg);
}

void *distributor(void *arg)
{
	char *msg;
	std::list<int>::iterator it;			
	
	while (true)
	{
		msg = pop_from_buffer();
		pthread_mutex_lock(&usr_lock);
		for (it = sock_list.begin(); it != sock_list.end(); it++)
		{
			if (write(*it, msg, strlen(msg)) < 0)
				oops("write");
		}
		del_from_buffer(msg);
		pthread_mutex_unlock(&usr_lock);
	}
}


